<script setup>
import { nextTick, onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import useInstance from '@/hooks/userInstance'
import {
  addApi,
  getParentApi,
  getListApi,
  editApi,
  deleteApi
} from '@/api/permission'
import throttle from 'lodash/throttle.js'
import { defaultProps } from 'element-plus/es/components/select-v2/src/useProps'
//获取全局global
const { global } = useInstance()
//获取上级菜单数据
const treeList = ref([])
const getParent = async () => {
  let res = await getParentApi()
  if (res) {
    treeList.value = res.data
  }
}
//新增表单对象
const addModel = reactive({
  id: '',
  parentId: '',
  comment: '',
  path: '',
  type: '',
  icon: '',
  name: '',
  sort: '',
  url: ''
})
//重置表单数据
const resetForm = () => {
  addModel.id = ''
  addModel.parentId = ''
  addModel.comment = ''
  addModel.path = ''
  addModel.type = ''
  addModel.icon = ''
  addModel.sort = ''
  addModel.url = ''
  addModel.name = ''
}
//新增表单属性
const addRef = ref()
//验证序号
const isNum = (rule, value, callback) => {
  const age = /^[0-9]*$/
  if (!age.test(value)) {
    callback(new Error('只能为数字'))
  } else {
    callback()
  }
}
//表单规则
const rules = ref({
  parentId: [
    {
      required: true,
      message: '选择上级菜单',
      trigger: 'blur'
    }
  ],
  comment: [
    {
      required: true,
      message: '请输入菜单备注',
      trigger: 'blur'
    }
  ],
  path: [
    {
      required: true,
      message: '请输入路由路径',
      trigger: 'blur'
    }
  ],
  type: [
    {
      required: true,
      message: '请选择组件类型',
      trigger: 'blur'
    }
  ],
  icon: [
    {
      required: true,
      message: '请选择图标',
      trigger: 'blur'
    }
  ],
  name: [
    {
      required: true,
      message: '请输入路径名称',
      trigger: 'blur'
    }
  ],
  sort: [
    {
      required: true,
      message: '请输入序号',
      trigger: 'blur'
    },
    { validator: isNum, trigger: 'blur' }
  ],
  url: [
    {
      required: true,
      message: '请输入组件路径',
      trigger: 'blur'
    }
  ]
})
//判断是新增还是编辑,0为新增，1为编辑
const tags = ref('')
//新增弹窗开关状态
let addFormShow = ref(false)
//表单标题
let menuTitle = ref('')
//表格高度
const tableHigh = ref(0)

//新增按钮
const addBtn = throttle(() => {
  resetForm()
  tags.value = '0'
  //获取上级菜单
  getParent()
  addFormShow.value = true
  menuTitle.value = '新增菜单'
}, 1000)
//编辑按钮
const editBtn = throttle(async row => {
  addModel.roleId = row.id
  tags.value = '1'
  addFormShow.value = true
  menuTitle.value = '编辑菜单'
  //回显数据
  await getParent()
  addModel.id = row.id
  addModel.parentId = row.parentId
  addModel.comment = row.comment
  addModel.path = row.path
  addModel.type = row.type
  addModel.icon = row.icon
  addModel.name = row.name
  addModel.sort = row.sort
  addModel.url = row.url
}, 1000)
//删除按钮
const deleteBtn = throttle(async permission => {
  const confirm = await global.$myConfirm('确定要删除吗？')
  let permissionId = permission.id
  if (confirm) {
    await deleteApi(permissionId)
    ElMessage.success('删除成功')
    await getList()
  }
}, 1000)
//表单提交
const submitForm = throttle(() => {
  addRef.value.validate(async valid => {
    if (valid) {
      if (tags.value === '0') {
        //新增
        let res = addApi(addModel)
        if (res) {
          addFormShow.value = false
          ElMessage.success('新增成功')
          await getList()
        }
        resetForm()
      } else {
        //编辑
        let res = await editApi(addModel)
        if (res) {
          addFormShow.value = false
          ElMessage.success('编辑成功')
          await getList()
        }
      }
      await getList()
    }
  })
}, 1000)
//表单关闭
const closeForm = throttle(() => {
  addFormShow.value = false
  resetForm()
}, 1000)
let tableList = ref([])
const getList = async () => {
  let res = await getListApi()
  console.log(res.data)
  tableList.value = res.data
}

onMounted(() => {
  nextTick(() => {
    tableHigh.value = window.innerHeight
  })
  getList()
})

// 使用 ref 创建响应式变量
const iconNames = ref([])

onMounted(() => {
  // 从文件夹中获取所有的svg图标路径，形成文件名数组，供选择菜单图标时显示
  // 注意替换文件路径！！！
  const files = import.meta.glob('@/assets/*.svg', { eager: true })
  for (const path in files) {
    iconNames.value.push(
      path.substring(path.lastIndexOf('/') + 1, path.lastIndexOf('.'))
    )
  }
})
</script>

<template>
  <el-main>
    <el-button icon="Plus" type="primary" @click="addBtn" style="float: right"
      >新增</el-button
    >
    <!-- 表格 -->
    <el-table
      default-expand-all
      :height="tableHigh"
      :data="tableList"
      row-key="id"
      style="width: 100%"
    >
      <el-table-column prop="comment" label="菜单名称" min-width="12%" />
      <el-table-column prop="icon" label="菜单图标" min-width="5%">
        <template #default="scope">
          <el-icon v-if="scope.row.icon">
            <component :is="scope.row.icon" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" min-width="10%">
        <template #default="scope">
          <el-tag v-if="scope.row.type === '0'" type="success">目录</el-tag>
          <el-tag v-if="scope.row.type === '1'" type="primary">菜单</el-tag>
          <el-tag v-if="scope.row.type === '2'" type="danger">按钮</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="路由名称" prop="name" min-width="10%" />
      <el-table-column label="路由地址" prop="path" min-width="15%" />
      <el-table-column label="组件路径" prop="url" min-width="15%" />
      <el-table-column label="序号" prop="sort" min-width="5%" />

      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button
            link
            type="success"
            icon="Edit"
            size="small"
            @click="editBtn(scope.row)"
            >编辑</el-button
          >
          <el-button
            link
            type="danger"
            icon="Delete"
            size="small"
            @click="deleteBtn(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </el-main>
  <!--  新增，编辑弹窗-->
  <el-dialog v-model="addFormShow" :title="menuTitle" width="50%">
    <el-form
      :model="addModel"
      ref="addRef"
      :rules="rules"
      label-width="120px"
      size="default"
      :inline="false"
    >
      <el-form-item prop="type" label="菜单类型：">
        <el-radio-group v-model="addModel.type">
          <el-radio label="0">目录</el-radio>
          <el-radio label="1">菜单</el-radio>
          <el-radio label="2">按钮</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-row>
        <el-col :span="11">
          <el-form-item prop="parentId" label="上级菜单：">
            <el-select
              v-model="addModel.parentId"
              @visible-change="handleSelectVisible"
            >
              <el-option>
                <el-tree
                  :data="treeList"
                  :props="defaultProps"
                  @node-click="handleNodeClick"
                ></el-tree>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="comment" label="菜单名称：">
            <el-input
              v-model="addModel.comment"
              placeholder="请输入菜单名称，例如聊天室"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item
            v-if="addModel.type !== '2'"
            prop="icon"
            label="菜单图标："
          >
            <el-select v-model="addModel.icon" placeholder="请选择菜单图标">
              <el-option
                v-for="item in iconNames"
                :key="item"
                :label="item"
                :value="item"
              >
                <div class="option-container">
                  <el-icon>
                    <component :is="item" />
                  </el-icon>
                  <span>&nbsp;&nbsp;{{ item }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            v-if="addModel.type !== '2'"
            prop="name"
            label="路由名称："
          >
            <el-input
              v-model="addModel.name"
              placeholder="请输入路由名称,例如Chat"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item prop="sort" label="菜单序号：">
            <el-input
              v-model="addModel.sort"
              placeholder="请输入菜单序号，例如5"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            v-if="addModel.type !== '2'"
            prop="path"
            label="路由地址："
          >
            <el-input
              v-model="addModel.path"
              placeholder="请输入路由地址，例如/example/Chat"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeForm">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss"></style>
